package com.example.service.impl;

import cn.hutool.http.HttpStatus;
import com.example.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 表示当前类是异常处理类，给Controller控制器类增强功能的
 * @author long
 * @date 2024/5/29 19:08
 */
@Slf4j
@Order(-1)
@RestControllerAdvice
public class CustomExceptionHandler {

    /**
     * 定义处理异常的方法，当异常发生后，执行这个方法
     * 处理NameException异常
     *
     * @ExceptionHandler: 表示此方法处理相应的异常
     *               属性: value 表示异常的类型
     *               位置: 在方法的上面
     */
    @ExceptionHandler(value = RuntimeException.class)
    public Object doNameException(Exception e) {
        log.error("CustomExceptionHandler-RuntimeException",e);
        return Result.builder().code(HttpStatus.HTTP_BAD_REQUEST).errorMsg(e.getMessage()).build();
    }

    //处理其他异常
    @ExceptionHandler(value = Exception.class)
    public Object doOtherException(Exception e) {
        log.error("CustomExceptionHandler-Exception",e);
        return Result.builder().code(HttpStatus.HTTP_BAD_REQUEST).errorMsg(e.getMessage()).build();
    }

    /**
     * 处理请求参数格式错误
     *
     * @param e @RequestBody上validate失败后抛出的异常
     * @return Object 同步返回500，异步返回JSON
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        return Result.builder().code(HttpStatus.HTTP_BAD_REQUEST).errorMsg(fieldError.getDefaultMessage()).build();
    }

    /**
     * 处理请求参数格式错误
     *
     * @param e @RequestParam上validate失败后抛出的此异常
     * @return Object 同步返回500，异步返回JSON
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Object handleConstraintViolationException(ConstraintViolationException e) {
        ConstraintViolation<?> constraintViolation = e.getConstraintViolations().iterator().next();
        return Result.builder().code(HttpStatus.HTTP_BAD_REQUEST).errorMsg(constraintViolation.getMessage()).build();
    }

}
